from astral.Net import TCPServer,errors
import socket
import threading
import time

class MastermindTCPAdapter(TCPServer):
    def __init__(self,gameserver,host="127.0.0.1",port=1919):
        TCPServer.__init__(self)
        self.gameserver = gameserver
        self.host = host
        self.port = port
    def sendback(self,data):
        self.send_data(data)
    def send_to_socket(self,sock,data):
        self.sending_socket = sock
        self.send_data(data)
    def remove_socket(self,sock):
        """Add a try except here"""
        try:
            TCPServer.remove_socket(self,sock)
        except ValueError:
            import traceback
            traceback.print_exc()
    def input_func(self,sock,host,port,address):
        """This occurs for each socket we hear from right before handle_data is called"""
        self.addr = address
        self.Send = lambda data:self.send_to_socket(sock,data)
    def handle_data(self,data,addr=None,send=None):
        """This occors on incoming data, right after input_func is called, but only if data is clean"""
        if not addr:
            addr = self.addr
        if not send:
            send = self.Send
        self.gameserver.handle_data(self.addr,self.Send,data)
    def client_disconnect_func(self,sock,host,port,address):
        """Client disconnected"""
        self.handle_data({"action":"disconnected"},addr=address,send=lambda data:0)
    def update(self):
        #The threads should already be listening
        pass
    def start(self):
        self.connect(self.host,self.port)
        self.serve_forever()
        self.quit()
        print "ending start"
    def start_threads(self):
        t = threading.Thread(target=self.start)
        t.daemon = True
        t.start()
        
        
from astral.PodSixNet.Channel import Channel
from astral.PodSixNet.Server import Server

class ClientChannel(Channel):
    player = None
    def Network(self, data):
        self._server.gameserver.handle_data(self.addr,self.Send,data)
    def handle_close(self):
        self.Network({"action":"disconnected"})
        Channel.handle_close(self)

class PodSixTCPAdapter(Server):
    channelClass = ClientChannel
    def __init__(self,gameserver,host="127.0.0.1",port=1919):
        Server.__init__(self,None,(host,port))
        self.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 0)
        self.gameserver = gameserver
    def update(self):
        self.Pump()
